/* eslint-disable no-nested-ternary */
import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import {Button, Form, Row, Col, Card, Spin, Table, Modal} from 'antd';
import {getDetail, getAreas, getAreasSimple} from './api';
import {FORM_OPTIONS, TABLE, FORM_ROW_OPTIONS, DATE_FORMAT} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {PERMISSIONS} from './constants';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import InputAmount from '../common/InputAmount';
import WrappedDatePicker from '../common/WrappedDatePicker';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import {currency, lcKind, isYesNo, lcOfficialDraftType, lcPayMentDays, multiLevelApproveResultJudgeResult} from '../Enum';
import FileUpload from './FileUpload';
import SearchSelectPanel from '../common/DutyUnitSelect/SelectEdit';
import {conventEnumValueToString, formatDateTime} from '../utils';
import {draftValidator} from './validator';
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {},
        approveResultDetails: []
    };

    componentDidMount() {
        this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id) {
            this.setState(({
                loading: true
            }));
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok) {
                        if(typeof res.data.isAllowBatch === 'boolean')
                            res.data.isAllowBatch = (res.data.isAllowBatch === true ? 1 : 0);
                        if(typeof res.data.isAllowTransfer === 'boolean')
                            res.data.isAllowTransfer = (res.data.isAllowTransfer === true ? 1 : 0);
                        this.setState({
                            loading: false,
                            data: Object.assign({}, res.data, {
                                isStatus: false
                            }),
                            approveResultDetails: res.data.approveResultDetails
                        });
                    } else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    handleFilterChange = (value, name) => {
        if(name === 'lcCode' || name === 'remark') {
            const data = Object.assign({}, this.state.data, {
                [name]: value
            });
            this.setState({
                data,
                hasOperat: true
            });
        } else {
            const data = Object.assign({}, this.state.data, {
                [name]: value,
                isStatus: true
            });
            this.setState({
                data,
                hasOperat: true
            });
        }
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onSelectCountry = value => {
        const data = Object.assign({}, this.state.data, {
            issueCountryId: value.id,
            issueCountryChineseName: value.chineseName
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    
    onSubmit = () => {
        const isValid = draftValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        if(this.state.data.isStatus)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'newPanel.message.switch1',
                    defaultMessage: '提示'
                }),
                content: this.props.intl.formatMessage({
                    id: 'newPanel.message.update',
                    defaultMessage: '已修改除信用证号码之外的字段, 需要重新审核, 需要继续吗?'
                }),
                onOk: () => this.props.onSubmitDraft(this.state.data).then(() => {
                    if(this.success)
                        this.props.successReturn();
                    if(!this.isunmount)
                        this.setState({loading: false});
                }),
                onCancel: () => this.setState({loading: false})
            });
        else
            this.props.onSubmitDraft(this.state.data).then(() => {
                if(this.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
    }
    
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    render() {
        const {data, approveResultDetails} = this.state;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const areaInfo = data.issueCountryId ? {
            id: data.issueCountryId,
            chineseName: data.issueCountryChineseName
        } : null;
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validateIssueDate = !data.issueDate && this.state.validate ? 'error' : null;
        const validateIssuePrice = !data.issuePrice && this.state.validate ? 'error' : null;
        const validateLcCode = !data.lcCode && this.state.validate ? 'error' : null;
        const validateIssueCountry = !data.issueCountryId && this.state.validate ? 'error' : null;
        const validateIssueBank = !data.issueBank && this.state.validate ? 'error' : null;
        const validateDateOfExpiry = !data.dateOfExpiry && this.state.validate ? 'error' : null;
        const validateLcKind = !data.lcKind && this.state.validate ? 'error' : null;
        const validateCurrency = !data.currency && this.state.validate ? 'error' : null;
        const validateLcPayMentDays = !data.lcPayMentDays && this.state.validate ? 'error' : null;
        const validateIsAllowBatch = !data.isAllowBatch && typeof data.isAllowBatch !== 'number' && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission, initEnum} = this.props;
        if(!data.id && initEnum.brands.length === 1) {
            data.brandId = initEnum.brands[0].id;
            data.brandCode = initEnum.brands[0].code;
            data.brandName = initEnum.brands[0].name;
        }
        const submitable = hasPermissions(PERMISSIONS.draft, pagePermission);
        const columsapprove = [{
            title: formatMessage({
                id: 'newPanel.column.approveSequence',
                defaultMessage: '审核序号'
            }),
            dataIndex: 'approveSequence'
        }, {
            title: formatMessage({
                id: 'newPanel.column.approverCode',
                defaultMessage: '审核人编号'
            }),
            dataIndex: 'approverCode'
        }, {
            title: formatMessage({
                id: 'newPanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName'
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment'
        }, {
            title: formatMessage({
                id: 'newPanel.column.approveResult',
                defaultMessage: '判定结果'
            }),
            dataIndex: 'approveResult',
            render: text => conventEnumValueToString(multiLevelApproveResultJudgeResult, text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.nextOperation',
                defaultMessage: '下一步操作'
            }),
            dataIndex: 'nextOperation'
        }];

        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                {initEnum.brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required>
                                        {this.props.id ? `(${data.brandCode})${data.brandName}`
                                            : <WrappedSelect
                                                allowClear
                                                name="brandId"
                                                value={data.brandId}
                                                options={initEnum.brands}
                                                onChange={this.handleFilterChange}/>
                                        }
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDealer} required>
                                        {this.props.id ? `(${data.dealerCode})${data.dealerName}`
                                            : <DealerSelectPanel
                                                value={dealerInfo}
                                                onChange={this.handleFilterChange}
                                                onSelect={this.onSelectDealer} />
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lcCode',
                                            defaultMessage: '信用证号码 '
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateLcCode} required>
                                        {<TextInput
                                            name="lcCode"
                                            value={data.lcCode}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.issueCountry',
                                            defaultMessage: '开证国家'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateIssueCountry} required>
                                        {<SearchSelectPanel
                                            value={areaInfo}
                                            isCountry={true}
                                            getDutyUnits={getAreas}
                                            getDutyUnitSimple={getAreasSimple}
                                            titleName={formatMessage({
                                                id: 'newPanel.form.issueCountry',
                                                defaultMessage: '开证国家'
                                            })}
                                            onSelect={this.onSelectCountry} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.issueBank',
                                            defaultMessage: '开证银行'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateIssueBank} required>
                                        {<TextInput
                                            name="issueBank"
                                            value={data.issueBank}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.issuePrice',
                                            defaultMessage: '开证金额'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateIssuePrice} required>
                                        {<InputAmount
                                            name="issuePrice"
                                            value={data.issuePrice}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.currency',
                                            defaultMessage: '币种'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateCurrency} required>
                                        {<WrappedSelect
                                            allowClear
                                            name="currency"
                                            value={data.currency}
                                            options={currency.toList(language)}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lcPayMentDays',
                                            defaultMessage: '信用证账期'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateLcPayMentDays} required>
                                        {<WrappedSelect
                                            allowClear
                                            name="lcPayMentDays"
                                            value={data.lcPayMentDays}
                                            options={lcPayMentDays.toList(language)}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.issueDate',
                                            defaultMessage: '开证日期'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateIssueDate} required>
                                        {<WrappedDatePicker
                                            name="issueDate"
                                            value={data.issueDate}
                                            onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lastLoadDate',
                                            defaultMessage: '最迟装船日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {<WrappedDatePicker
                                            name="lastLoadDate"
                                            value={data.lastLoadDate}
                                            onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.shippingPortId',
                                            defaultMessage: '起运港'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {<WrappedSelect
                                            allowClear
                                            name="shippingPortId"
                                            value={data.shippingPortId}
                                            options={initEnum.shippingPorts}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.destinationPort',
                                            defaultMessage: '目的港'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {<TextInput
                                            name="destinationPort"
                                            value={data.destinationPort}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.isAllowBatch',
                                            defaultMessage: '是否允许分批'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateIsAllowBatch} required>
                                        {<WrappedSelect
                                            allowClear
                                            name="isAllowBatch"
                                            value={data.isAllowBatch}
                                            options={isYesNo.toList(language)}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.isAllowTransfer',
                                            defaultMessage: '是否允许转运'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {<WrappedSelect
                                            allowClear
                                            name="isAllowTransfer"
                                            value={data.isAllowTransfer}
                                            options={isYesNo.toList(language)}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'newPanel.text.quantity',
                                        defaultMessage: '件数'
                                    })} {...FORM_OPTIONS.item}>
                                        {<LocalizeInputNumber
                                            min={0}
                                            name="quantity"
                                            value={data.quantity}
                                            onChange={this.handleFilterChange}/>}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dateOfExpiry',
                                            defaultMessage: '效期'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDateOfExpiry} required>
                                        {<WrappedDatePicker
                                            name="dateOfExpiry"
                                            value={data.dateOfExpiry}
                                            onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.placeOfExpiry',
                                            defaultMessage: '效地'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {<TextInput
                                            name="placeOfExpiry"
                                            value={data.placeOfExpiry}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lcOfficialDraftType',
                                            defaultMessage: '正本草本'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(lcOfficialDraftType, data.lcOfficialDraftType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.lcKind',
                                            defaultMessage: '信用证类型'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateLcKind} required>
                                        {conventEnumValueToString(lcKind, data.lcKind)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.commodityDescription',
                                            defaultMessage: '货描'
                                        })}
                                        {...FORM_ROW_OPTIONS.item}>
                                        {(this.props.page === 'approve' || this.props.page === 'finance') ? data.commodityDescription : <TextInput
                                            name="commodityDescription"
                                            type="textarea"
                                            value={data.commodityDescription}
                                            onBlur={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.remark',
                                            defaultMessage: '备注'
                                        })}
                                        {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            name="remark"
                                            type="textarea"
                                            value={data.remark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card title={formatMessage({
                            id: 'newPanel.card.approveResult',
                            defaultMessage: '审核记录'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columsapprove}
                                rowKey="id"
                                pagination={false}
                                dataSource={approveResultDetails}
                                {...TABLE} />
                        </Card>
                        <Card title={formatMessage({
                            id: 'newPanel.title.files',
                            defaultMessage: '附件清单'
                        })}>
                            {<Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeUpload}
                                        onRemove={this.removeFilePath}
                                        fileList={data.attachments || []}/>
                                </Col>
                            </Row>}
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'newPanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmitDraft: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    draft,
    tableSearch
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        const shippingPorts = initData.shippingPorts ? initData.shippingPorts.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
            shippingPorts
        };
    }
);
const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    initEnum: getinitEnumData(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmitDraft: data => dispatch(draft(data)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url()),
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
